<?php
/**
 * Created by PhpStorm.
 * User: ZZF
 * Date: 2017/12/8
 * Time: 13:52
 */
namespace app\home\model;
use think\Model;
class UserModel extends Model{

    /**
     * 获取用户默认收货地址
     * @param $user_id
     */
    public function getDefaultAddress($user_id){
        $address = db('UserAddress')
            ->alias('a')
            ->join('__REGION__ r','r.id = a.province or r.id = a.city or r.id = a.district','LEFT')
            ->where(['user_id'=>$user_id,'is_default'=>1])
            ->field('a.*,group_concat(r.name SEPARATOR "") as region_address')
            ->find();
        return $address;
    }

    /**
     * 获取用户可用优惠券
     * @param $user_id
     * @param $consumption 消费金额
     * @return mixed
     */
    public function getUsableCoupon($user_id){
        $where['user_id'] = $user_id;
        $where['status'] = 1;
        $list = db('UserCoupon')
            ->alias('uc')
            ->join('__GOODS__ g','g.id = uc.goods_id','LEFT')
            ->field('uc.*,g.goods_name')
            ->where($where)
            ->select();
        return $list;
    }

    /**
     * 验证优惠券是否可用
     * @param $user_id
     * @param $cart
     * @param $coupon_id
     * @return bool 优惠券金额
     */
    public function checkCoupon($user_id,$cart,$coupon_id){
        $flag = false;
        if(!$goods_id = db('UserCoupon')->where(['user_id'=>$user_id,'id'=>$coupon_id,'status'=>1])->value('goods_id')){
            return false;
        }
        $price = 0;
        foreach($cart['cartList'] as $item){
            if($item['goods_id'] == $goods_id){
                $flag = true;
                $price = $item['price'];
            }
        }

        if($flag == false){
            return false;
        }else{
            return $price;
        }
    }

    /**
     * 获取用户可用积分
     * @param $user_id
     * @param $consumption
     * @return mixed
     */
    public function getUserIntegral($user_id,$consumption){
        $integral = $this->where(['id'=>$user_id])->value('integral');
        $point_rate = db('System')->where(['id'=>1])->value('point_rate');
        $needIntegral = $consumption * $point_rate;
        return $integral > $needIntegral ? $needIntegral : $integral;
    }
}